<?php

define('ACTION_APPROVE', 0);
define('ACTION_DISCARD', 1);
define('ACTION_IGNORE', 2);

class AdminController extends AppController
{
	var $name = 'Admins';
	var $uses = array('User', 'Quote');
	var $helpers = array('Html', 'Form');
	
	function index()
	{
		$this->checkRights();
		$this->set('title', 'Admin panel');
	}
	
	function users()
	{
		$this->checkRights();
		
		if(!empty($this->data['User']))
		{
			if($this->User->save($this->data['User']))
			{
				$this->flash('Admin "' . $this->data['User']['name'] . '"added.', '/admin/users');
				exit();
			}
		}

		$users = $this->User->findAll('access = 1', null, 'name ASC');
		$this->set('users', $users);
		$this->set('title', 'Manage users');
	}
	
	function deop($id)
	{
		$this->checkLock();
		$this->checkRights();
		$user = array('id' => $id, 'access' => 0);

		if($this->User->save($user))
		{
			$this->flash('This user has been deopped.', '/admin/users');
		}
	}
	
	function approve()
	{
		$this->checkLock();
		$this->checkRights();
		$table = $this->Quote->tablePrefix . $this->Quote->table;

		if(isset($_POST['approve-all']))
		{
			$this->Quote->execute("UPDATE " . $table . " SET status = '" . QUOTE_STATUS_NORMAL . "' WHERE status = '" . QUOTE_STATUS_UNAPPROVED . "'");
		}
		else if(isset($_POST['discard-all']))
		{
			$this->Quote->execute("UPDATE " . $table . " SET status = '" . QUOTE_STATUS_DELETED . "' WHERE status = '" . QUOTE_STATUS_UNAPPROVED . "'");
		}
		else if(isset($_POST['update']))
		{
			foreach($_POST['approve'] as $id => $action)
			{
				if($action == ACTION_IGNORE)
					continue;
			
				$this->Quote->id = $id;
				$data = $this->Quote->read();

				if($action == ACTION_APPROVE)
				{
					$data['Quote']['status'] = QUOTE_STATUS_NORMAL;
				}
				else if($action == ACTION_DISCARD)
				{
					$data['Quote']['status'] = QUOTE_STATUS_DELETED;
					$data['Quote']['deleted'] = date('Y-m-d H:i:s');
				}
				
				$this->Quote->save($data);
			}
		}
		
		$this->flash('Operation completed.', '/admin');
	}
}

?>
